<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>后台管理 - 网上跳蚤市场</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>
<div th:replace="layout :: .nav"></div>
<div class="container">
    <section>
        <h2>后台管理</h2>
        <div class="admin-tabs">
            <button class="tab-btn active" data-tab="products">商品管理</button>
            <button class="tab-btn" data-tab="categories">分类管理</button>
            <button class="tab-btn" data-tab="reviews">评价管理</button>
            <button class="tab-btn" id="userTabBtn" style="display:none" data-tab="users">用户管理</button>
        </div>

        <div class="tab-content" id="products-tab">
            <h3>商品管理</h3>
            <div id="productsList"></div>
        </div>

        <div class="tab-content" id="categories-tab" style="display:none">
            <h3>分类管理</h3>
            <div id="categoriesList"></div>
            <div id="categoryForm">
                <h4>添加分类</h4>
                <input type="text" id="categoryName" placeholder="分类名称">
                <input type="text" id="categoryDesc" placeholder="分类描述">
                <button id="addCategoryBtn">添加</button>
            </div>
        </div>

        <div class="tab-content" id="reviews-tab" style="display:none">
            <h3>评价管理</h3>
            <div id="reviewsList"></div>
        </div>

        <div class="tab-content" id="users-tab" style="display:none">
            <h3>用户管理</h3>
            <div id="usersList"></div>
        </div>
    </section>
</div>
<style>
    .admin-tabs {
        display: flex;
        margin-bottom: 30px;
        justify-content: center; /* 居中显示 */
        gap: 15px; /* 按钮之间的间距 */
    }

    .tab-btn {
        padding: 15px 0; /* 上下增加内边距 */
        cursor: pointer;
        background: #ffcccc;/*按钮背景色*/
        border: none;
        border-radius: 6px; /* 圆角 */
        font-size: 16px; /* 增大字体 */
        font-weight: 500;
        width: 180px; /* 固定宽度 */
        transition: all 0.3s;
        box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    }

    .tab-btn:hover {
        background: #bae7ff; /* 悬停时的背景色 */
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }

    .tab-btn.active {
        background: #1890ff; /* 深蓝色 */
        color: white;
        box-shadow: 0 4px 10px rgba(24, 144, 255, 0.3);
    }

    .tab-content { display: none; }
    #products-tab { display: block; }
    .btn-danger { background-color: #dc3545; color: white; }

    .status-badge {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: bold;
        text-transform: uppercase;
    }

    .status-badge.pending {
        background-color: #ffc107;
        color: #212529;
    }

    .status-badge.approved {
        background-color: #28a745;
        color: white;
    }

    .status-badge.rejected {
        background-color: #dc3545;
        color: white;
    }

    .admin-section {
        background-color: white;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        margin-bottom: 25px;
    }

    .role-select {
        padding: 5px;
        border: 1px solid #ddd;
        border-radius: 4px;
        margin-right: 5px;
    }

    .success-msg {
        background-color: #d4edda;
        color: #155724;
        padding: 10px 15px;
        border-radius: 4px;
        margin: 15px 0;
        border: 1px solid #c3e6cb;
        font-weight: 500;
    }

    .error-msg {
        background-color: #f8d7da;
        color: #721c24;
        padding: 10px 15px;
        border-radius: 4px;
        margin: 15px 0;
        border: 1px solid #f5c6cb;
        font-weight: 500;
    }

    /* 顶部悬浮提示样式 */
    .toast-container {
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        z-index: 9999;
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 80%;
        max-width: 500px;
    }

    .toast-message {
        width: 100%;
        padding: 15px;
        border-radius: 5px;
        margin-bottom: 10px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        animation: fadeIn 0.3s, fadeOut 0.5s 1.5s forwards;
    }

    .toast-success {
        background-color: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }

    .toast-error {
        background-color: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }

    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(-20px); }
        to { opacity: 1; transform: translateY(0); }
    }

    @keyframes fadeOut {
        from { opacity: 1; transform: translateY(0); }
        to { opacity: 0; transform: translateY(-20px); visibility: hidden; }
    }
</style>

<div id="toastContainer" class="toast-container"></div>

<script>
    // 显示顶部悬浮提示
    function showToast(message, type = 'success') {
        const toastContainer = document.getElementById('toastContainer');

        // 创建提示元素
        const toast = document.createElement('div');
        toast.className = `toast-message toast-${type}`;
        toast.textContent = message;

        // 添加到容器
        toastContainer.appendChild(toast);

        // 2秒后自动移除
        setTimeout(() => {
            toast.remove();
        }, 2000);
    }

    let isAdmin = false;
    let isCategoryAdmin = false;

    // 检查用户角色
    async function checkRole() {
        try {
            const res = await fetch('/api/users/me', {
                credentials: 'include'
            });
            const user = await res.json();
            isAdmin = user.role === 'admin';
            isCategoryAdmin = user.role === 'category_admin';

            // 只有系统管理员可以看到用户管理选项卡
            if (isAdmin) {
                document.getElementById('userTabBtn').style.display = 'block';
            }
        } catch (e) {
            window.location.href = '/login'; // 未登录跳转登录页
        }
    }

    // Tab切换
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');

            document.querySelectorAll('.tab-content').forEach(tab => tab.style.display = 'none');
            document.getElementById(btn.dataset.tab + '-tab').style.display = 'block';

            if (btn.dataset.tab === 'products') loadProducts();
            if (btn.dataset.tab === 'categories') loadCategories();
            if (btn.dataset.tab === 'reviews') loadReviews();
            if (btn.dataset.tab === 'users' && isAdmin) loadUsers(); // 只有系统管理员才能加载用户管理
        });
    });

    // 商品列表与审核
    async function loadProducts() {
        const res = await fetch('/api/products/page?page=0&size=50', {
            credentials: 'include'
        });
        const data = await res.json();

        let html = '<table><tr><th>ID</th><th>名称</th><th>状态</th><th>卖家</th><th>操作</th></tr>';
        for (const p of data.content) {
            html += `<tr>
            <td>${p.id}</td>
            <td>${p.name}</td>
            <td>${p.status === 'on_sale' ? '已上架' : '已下架'}</td>
            <td>${p.user ? p.user.username : '未知'}</td>
            <td>
                ${p.status !== 'on_sale'
                ? `<button onclick="approveProduct(${p.id})">审核通过</button>`
                : `<button onclick="forceOffProduct(${p.id})">强制下架</button>`}
                <button onclick="deleteProduct(${p.id})" class="btn-danger">删除</button>
            </td>
        </tr>`;
        }
        html += '</table>';
        document.getElementById('productsList').innerHTML = html;
    }

    async function approveProduct(id) {
        try {
            const res = await fetch(`/api/products/${id}/approve`, {
                method: 'POST',
                credentials: 'include'
            });
            const data = await res.json();
            showToast('操作成功', 'success');
            loadProducts();
        } catch (e) {
            showToast('操作失败', 'error');
        }
    }

    async function forceOffProduct(id) {
        try {
            const res = await fetch(`/api/products/${id}/force-off`, {
                method: 'POST',
                credentials: 'include'
            });
            const data = await res.json();
            showToast('操作成功', 'success');
            loadProducts();
        } catch (e) {
            showToast('操作失败', 'error');
        }
    }

    async function deleteProduct(id) {
        if (!confirm('确定要删除这个商品吗？此操作不可恢复！')) {
            return;
        }

        try {
            const res = await fetch(`/api/products/${id}`, {
                method: 'DELETE',
                credentials: 'include'
            });

            if (!res.ok) {
                throw new Error(`服务器返回错误: ${res.status}`);
            }

            showToast('商品已删除', 'success');
            loadProducts();
        } catch (e) {
            console.error('删除商品失败:', e);
            showToast(`删除失败: ${e.message || '未知错误'}`, 'error');
        }
    }

    // 分类管理
    async function loadCategories() {
        const res = await fetch('/admin/categories', {
            credentials: 'include'
        });
        const data = await res.json();

        let html = '<table><tr><th>ID</th><th>名称</th><th>描述</th><th>操作</th></tr>';
        for (const c of data) {
            html += `<tr>
            <td>${c.id}</td>
            <td>${c.name}</td>
            <td>${c.description || ''}</td>
            <td><button onclick="deleteCategory(${c.id})">删除</button></td>
        </tr>`;
        }
        html += '</table>';
        document.getElementById('categoriesList').innerHTML = html;
    }

    async function deleteCategory(id) {
        try {
            await fetch(`/admin/categories/${id}`, {
                method: 'DELETE',
                credentials: 'include'
            });
            showToast('分类已删除', 'success');
            loadCategories();
        } catch (e) {
            showToast('操作失败', 'error');
        }
    }

    document.getElementById('addCategoryBtn').onclick = async () => {
        const name = document.getElementById('categoryName').value;
        const description = document.getElementById('categoryDesc').value;

        if (!name) {
            showToast('请输入分类名称', 'error');
            return;
        }

        try {
            const res = await fetch('/admin/categories', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify({ name, description })
            });
            const data = await res.json();

            showToast('分类已添加', 'success');
            document.getElementById('categoryName').value = '';
            document.getElementById('categoryDesc').value = '';
            loadCategories();
        } catch (e) {
            showToast('添加失败', 'error');
        }
    };

    // 评价管理
    async function loadReviews() {
        try {
            const res = await fetch('/api/reviews', {
                credentials: 'include'
            });
            const data = await res.json();

            let html = '<table><tr><th>ID</th><th>商品</th><th>评分</th><th>评价内容</th><th>评价时间</th><th>操作</th></tr>';
            for (const review of data) {
                const productName = review.order && review.order.product ? review.order.product.name : '未知商品';
                const avgScore = ((review.descriptionScore || 0) + (review.responseScore || 0)) / 2;

                html += `<tr>
                <td>${review.id}</td>
                <td>${productName}</td>
                <td>${avgScore.toFixed(1)}</td>
                <td>${review.comment || '无评价内容'}</td>
                <td>${new Date(review.createdAt).toLocaleString()}</td>
                <td><button onclick="deleteReview(${review.id})" class="btn-danger">删除</button></td>
            </tr>`;
            }
            html += '</table>';
            document.getElementById('reviewsList').innerHTML = html;
        } catch (e) {
            console.error('加载评价失败:', e);
            document.getElementById('reviewsList').innerHTML = '<p class="error-msg">加载评价失败</p>';
        }
    }

    async function deleteReview(id) {
        if (!confirm('确定要删除这条评价吗？此操作不可恢复！')) {
            return;
        }

        try {
            const res = await fetch(`/api/reviews/${id}`, {
                method: 'DELETE',
                credentials: 'include'
            });

            if (!res.ok) {
                throw new Error(`服务器返回错误: ${res.status}`);
            }

            showToast('评价已删除', 'success');
            loadReviews(); // 重新加载评价列表
        } catch (e) {
            console.error('删除评价失败:', e);
            showToast(`删除失败: ${e.message || '未知错误'}`, 'error');
        }
    }

    // 加载用户列表
    async function loadUsers() {
        const res = await fetch('/api/admin/users', {
            credentials: 'include'
        });
        const users = await res.json();

        let html = '<div class="admin-section"><h4>用户管理</h4>';
        html += '<table><tr><th>ID</th><th>用户名</th><th>角色</th><th>状态</th><th>注册时间</th><th>操作</th></tr>';

        // 先显示待审核用户
        const pendingUsers = users.filter(u => u.status === 'pending');
        for (const user of pendingUsers) {
            html += `<tr>
            <td>${user.id}</td>
            <td>${user.username}</td>
            <td>
                <select id="role-${user.id}" class="role-select">
                    <option value="user" ${user.role === 'user' ? 'selected' : ''}>普通用户</option>
                    <option value="category_admin" ${user.role === 'category_admin' ? 'selected' : ''}>分类管理员</option>
                    <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>系统管理员</option>
                </select>
                <button onclick="updateUserRole(${user.id})">更新角色</button>
            </td>
            <td><span class="status-badge pending">待审核</span></td>
            <td>${new Date(user.createdAt).toLocaleString()}</td>
            <td>
                <button onclick="approveUser(${user.id})">通过</button>
                <button onclick="rejectUser(${user.id})" class="btn-danger">拒绝</button>
                <button onclick="deleteUser(${user.id})" class="btn-danger">删除用户</button>
            </td>
        </tr>`;
        }

        // 然后显示已审核和已拒绝用户
        const otherUsers = users.filter(u => u.status !== 'pending');
        for (const user of otherUsers) {
            const statusText = user.status === 'approved' ? '<span class="status-badge approved">已审核</span>' : '<span class="status-badge rejected">已拒绝</span>';
            const actionBtn = user.status === 'approved'
                ? `<button onclick="rejectUser(${user.id})" class="btn-danger">拒绝</button>`
                : `<button onclick="approveUser(${user.id})">通过</button>`;

            html += `<tr>
            <td>${user.id}</td>
            <td>${user.username}</td>
            <td>
                <select id="role-${user.id}" class="role-select">
                    <option value="user" ${user.role === 'user' ? 'selected' : ''}>普通用户</option>
                    <option value="category_admin" ${user.role === 'category_admin' ? 'selected' : ''}>分类管理员</option>
                    <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>系统管理员</option>
                </select>
                <button onclick="updateUserRole(${user.id})">更新角色</button>
            </td>
            <td>${statusText}</td>
            <td>${new Date(user.createdAt).toLocaleString()}</td>
            <td>
                ${actionBtn}
                <button onclick="deleteUser(${user.id})" class="btn-danger">删除用户</button>
            </td>
        </tr>`;
        }

        html += '</table></div>';
        document.getElementById('usersList').innerHTML = html;
    }

    // 通过用户审核
    async function approveUser(id) {
        try {
            const res = await fetch(`/api/admin/users/${id}/approve`, {
                method: 'POST',
                credentials: 'include'
            });

            if (!res.ok) {
                throw new Error(`服务器返回错误: ${res.status}`);
            }

            showToast('已通过用户审核', 'success');
            loadUsers();
        } catch (e) {
            showToast(`操作失败: ${e.message || '未知错误'}`, 'error');
        }
    }

    // 拒绝用户审核
    async function rejectUser(id) {
        try {
            const res = await fetch(`/api/admin/users/${id}/reject`, {
                method: 'POST',
                credentials: 'include'
            });

            if (!res.ok) {
                throw new Error(`服务器返回错误: ${res.status}`);
            }

            showToast('已拒绝用户审核', 'success');
            loadUsers();
        } catch (e) {
            showToast(`操作失败: ${e.message || '未知错误'}`, 'error');
        }
    }

    // 更新用户角色
    async function updateUserRole(id) {
        const role = document.getElementById(`role-${id}`).value;

        try {
            const res = await fetch(`/api/admin/users/${id}/role?role=${role}`, {
                method: 'PUT',
                credentials: 'include'
            });

            if (!res.ok) {
                throw new Error(`服务器返回错误: ${res.status}`);
            }

            showToast('用户角色已更新', 'success');
            loadUsers();
        } catch (e) {
            showToast(`更新失败: ${e.message || '未知错误'}`, 'error');
        }
    }

    // 删除用户
    async function deleteUser(id) {
        if (!confirm('确定要删除这个用户吗？此操作不可恢复！')) {
            return;
        }

        try {
            const res = await fetch(`/api/admin/users/${id}`, {
                method: 'DELETE',
                credentials: 'include'
            });

            if (!res.ok) {
                // 尝试解析错误响应
                const errorData = await res.json().catch(() => ({}));
                const errorMessage = errorData.message || errorData.error || `服务器返回错误: ${res.status}`;
                throw new Error(errorMessage);
            }

            showToast('用户已成功删除', 'success');
            loadUsers();
        } catch (e) {
            console.error('删除用户失败:', e);
            showToast(`删除失败: ${e.message}`, 'error');
        }
    }

    checkRole().then(loadProducts);
</script>
</body>
</html> 